package com.rw.car.service.impl;

import com.rw.car.service.CarInfoService;
import com.rw.common.pojo.EsCarInfo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class CarInfoServiceImpl implements CarInfoService {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Override
    public List<EsCarInfo> findEsBy(EsCarInfo carInfo) {
        //是构建的查询条件
        //设置分页参数
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                .withPageable(PageRequest.of(0, 8));
        //构建多条件查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //动态的构建查询条件
        //如果车型不为空的时候，进行车型查询
        if (carInfo.getCarType() != null){
            for (String item:carInfo.getCarType().split(",")){
                MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("carType", item);
                boolQueryBuilder.should(matchQueryBuilder);
            }
        }
        //如果车龄不为空的时候，进行车龄查询
        if (carInfo.getCarYear() != null){
            for (String year:carInfo.getCarYear().split(",")){
                MatchQueryBuilder yearMatchQuery = QueryBuilders.matchQuery("carYear", year);
                boolQueryBuilder.should(yearMatchQuery);
            }
        }


        queryBuilder.withQuery(boolQueryBuilder);
        SearchHits<EsCarInfo> search = elasticsearchRestTemplate.search(queryBuilder.build(),
                EsCarInfo.class);
        List<SearchHit<EsCarInfo>> searchHits = search.getSearchHits();
        List<EsCarInfo> list = new ArrayList<>();
        for (SearchHit<EsCarInfo> searchHit : searchHits) {
            System.out.println(searchHit.getContent());
            list.add(searchHit.getContent());
        }
        return list;
    }
}
